<template>
	<view class="page">
    <!-- 商品评价 -->
    <view class="evaluate-goods">
      <view class="list">
        <view class="picture">
          <image :src="goodsInfo.thumb"></image>
        </view>
        <view class="rating-container">
          <view class="rating-title">商品评价</view>
          <view class="star-rating">
            <view class="stars">
              <text 
                v-for="index in 5" 
                :key="index"
                :class="[
                  'cuIcon-favorfill', 
                  'lg', 
                  index <= formData.rating ? 'filled' : 'hollow'
                ]"
                @click="handleRate(index)"
              ></text>
            </view>
            <text class="rating-label">{{ ratingText }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 评价输入 -->
    <view class="input-info">
      <view class="input-title">
        <text>分享你的使用体验吧</text>
      </view>
      <view class="input-text">
        <textarea 
          v-model="formData.content" 
          placeholder="感觉怎么？跟大家分享一下吧~"
          maxlength="200"
          @input="handleContentInput"
        ></textarea>
        <view class="record-text">
          <text>已写</text>
          <text class="ac">{{ contentLength }}</text>
          <text>个字</text>
        </view>
      </view>
      <view class="anonymous">
        <radio 
          :checked="formData.is_anonymous" 
          @click="formData.is_anonymous = !formData.is_anonymous"
          color="#007AFF"
        />
        <text>匿名评价</text>
      </view>
    </view>

    <!-- 图片上传 -->
    <view class="upload-img">
      <view class="img-title">
        <text>上传图片/视频（{{ formData.media.length }}/6）</text>
      </view>
      <view class="img-list">
        <!-- 上传按钮 -->
        <view 
          class="list up-img"
          @click="handleUpload"
          v-if="formData.media.length < 6"
        >
          <image src="/static/up_img.png"></image>
        </view>
        <!-- 已上传文件 -->
        <view 
          v-for="(item, index) in formData.media"
          :key="index"
          class="list"
          @click="handleRemoveMedia(index)"
        >
          <image :src="item.url" mode="aspectFill" />
          <text class="iconfont icon-close1"></text>
        </view>
      </view>
    </view>

    <!-- 提交按钮 -->
    <view class="submit-btn">
      <view 
        class="btn" 
        :class="{ disabled: !isFormValid }"
        @click="handleSubmit"
      >
        <text>提交</text>
      </view>
    </view>
	</view>
</template>

<script>
import comment from '../api/comment.js';

export default {
	  props: {
	    initialScore: {
	      type: Number,
	      default: 3 // 默认3星
	    }
	  },
  data() {
    return {
		files:[],
		order_id:1,
		object_id:101,
		object_type:2,
		user_id:1,
		rating:0,
		text:"",
		pid:0,
		goodsInfo: {
			id: 123,
			thumb: '/static/img/goods_thumb_01.png'
		},
		formData: {
			rating: this.initialScore,
			content: '',
			is_anonymous: false,
			media: [] // { type: 'image', url: '...' }
      },
      contentLength: 0,
	  comment_status:0
    };
  },
  computed: {
    ratingText() {
      const ratings = {
        1: '差评',
        2: '一般',
        3: '满意',
        4: '推荐',
        5: '强烈推荐'
      }
      return ratings[this.formData.rating] || '暂无评价'
    },
    isFormValid() {
      return this.formData.rating > 0 && 
             this.formData.content.length <= 200
    }
  },
  methods: {
    handleRate(score) {
      this.formData.rating = score
	  this.$emit('rate', score) // 触发rate事件，传递当前评分
	  this.rating=score
    },
    handleContentInput(e) {
      this.contentLength = e.detail.value.length
	  this.text=e.detail.value
    },
    // 上传文件
   async handleUpload() {
     try {
       // 从组件数据中获取最大允许上传数量（示例变量名，根据实际业务调整）
       const maxUpload = this.maxCount || 6; // 假设最大上传9个文件
       const remainingSlots = maxUpload - this.formData.media.length;
       // 如果无可上传空间则提示用户
       if (remainingSlots <= 0) {
         return uni.showToast({
           title: `最多可上传${maxUpload}个文件`,
           icon: 'none'
         });
       }
       // 选择文件并捕获结果
       const result = await uni.chooseImage({
         count: remainingSlots, // 使用剩余可上传数量
         sizeType: ['compressed'],
         sourceType: ['album', 'camera']
       });
       // 解构获得文件数组（根据uni-app文档结构调整）
       const { tempFiles } = result[1]; // 注意：不同平台返回值可能不同，需测试验证
       // 文件有效性验证
       const MAX_FILE_SIZE = 5 * 1024 * 1024; // 示例：5MB限制
       const validFiles = tempFiles.filter(file => {
         if (file.size > MAX_FILE_SIZE) {
           uni.showToast({
             title: `文件${file.name}超过大小限制`,
             icon: 'none'
           });
           return false;
         }
         return true;
       });
       // 转换文件格式并追加到现有列表
       const newMedia = validFiles.map(file => ({
         type: 'image',
         url: file.path,
         file,
         uploadStatus: 'pending' // 添加上传状态跟踪
       }));
       // 使用扩展运算符追加新文件（保留原有文件）
       this.formData.media = [...this.formData.media, ...newMedia];
       // 触发上传（建议添加上传队列控制）
       this.uploadFiles();
     } catch (error) {
       // 处理用户取消选择或其他错误
       if (error?.errMsg !== 'chooseImage:fail cancel') {
         console.error('文件选择失败:', error);
         uni.showToast({
           title: '文件选择失败',
           icon: 'none'
         });
       }
     }
   },
    // 上传文件
    async uploadFiles() {
      const pendingFiles = this.formData.media
      for (const file of pendingFiles) {
          file.status = 'uploading';
          const uploadTask = uni.uploadFile({
            url: 'http://127.0.0.1:8899/file/adds',
            filePath: file.url,
            name: 'files', // 与后端约定的字段名
            formData: {
              userId: 123, // 附加参数
              fileName: file.name
            },
            success: (res) => {
              if (res.statusCode === 200) {
                file.status = 'success';
				const f =JSON.parse(res.data)
				this.files = this.files.concat(f.data)
              } else {
                throw new Error('上传失败');
              }
            }
          });
          // 监听进度
          uploadTask.onProgressUpdate((res) => {
            file.progress = res.progress;
          });
          await uploadTask;
      }
    },
	// 删除文件
    handleRemoveMedia(index) {
		this.formData.media.splice(index, 1)
    },
    async handleSubmit() {
		comment.GetOrder({
			order_id:this.order_id,
		}).then(res=>{
			if(res.code==-1){
				alert("内部错误")
			}
			console.log("res",res.data)
			this.comment_status=res.data.commentStatus
			console.log("status",this.comment_status)
			if(this.comment_status==2){
				alert("此订单已评价")
				uni.navigateTo({
				  url: '/pages/MyOrderList/MyOrderList?type='+4
				})
				return
			}else{
				comment.commentAdd({
					object_id:this.object_id,
					object_type:this.object_type,
					file:this.files,
					user_id:this.user_id,
					rating:this.rating,
					text:this.text,
					// pid:0,
					order_id:this.order_id,
				})
				uni.navigateTo({
					url: '/pages/MyOrderList/MyOrderList?type='+4
				})
			}
		})
		
      try {
        // 添加媒体文件
        this.formData.media.forEach((item, index) => {
          form.append(`media[${index}]`, item.file)
        })
        // 显示加载状态
        uni.showLoading({ title: '提交中...', mask: true })
        // 调用API
        const { code, message } = await comment.submitEvaluation(form)
        console.log(code,message)
        if (code === 200) {
          uni.showToast({ title: '评价成功' })
          setTimeout(() => uni.navigateBack(), 1500)
        } else {
          throw new Error(message)
        }
        uni.hideLoading()
      } catch (error) {
        uni.showToast({
          title: error.message || '提交失败',
          icon: 'none'
        })
      }
    }
  },
  
}
</script>

<style scoped lang="scss">
@import "MyEvaluatePush.scss";
</style>